package com.hunan.api.catv.service.impl.wx;

import com.google.gson.JsonObject;
import com.hunan.api.catv.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxService {

    @Autowired
    RestTemplate restTemplate;

    public static Logger log = LoggerFactory.getLogger(WxService.class);

    public JsonObject getAccessToken(String domain, String appid, String secret, String code) {
        StringBuilder url = new StringBuilder(domain);
        url.append("/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type={grant_type}");
        Map<String, String> uriVariables = new HashMap<String, String>();
        uriVariables.put("appid", appid);
        uriVariables.put("secret", secret);
        uriVariables.put("code", code);
        uriVariables.put("grant_type", "authorization_code");
        HttpEntity<String> requestEntity = new HttpEntity<String>("");
        ResponseEntity<String> result = restTemplate.exchange(url.toString(), HttpMethod.GET, requestEntity, String.class, uriVariables);
        if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
            return GsonUtils.fromJson(result.getBody(), JsonObject.class);
        }
        return null;
    }

    public JsonObject getUserinfo(String domain, String token, String openid) {
        StringBuilder url = new StringBuilder(domain);
        url.append("/sns/userinfo?access_token={token}&openid={openid}");
        Map<String, String> uriVariables = new HashMap<String, String>();
        uriVariables.put("token", token);
        uriVariables.put("openid", openid);
        HttpEntity<String> requestEntity = new HttpEntity<String>("");
        ResponseEntity<String> result = restTemplate.exchange(url.toString(), HttpMethod.GET, requestEntity, String.class, uriVariables);
        if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
            return GsonUtils.fromJson(result.getBody(), JsonObject.class);
        }
        return null;
    }
}
